#include "stringHandler.h"
#include "cpuSimulator.h"
#include <QDebug>

// 哈希算法映射初始化
const QMap<int, QCryptographicHash::Algorithm> StringHandler::hashAlgorithmMap = {
    {1, QCryptographicHash::Md5},
    {2, QCryptographicHash::Sha1},
    {3, QCryptographicHash::Sha256},
    {4, QCryptographicHash::Sha512}
};

/**
 * @brief StringHandler构造函数
 * @param parent 父对象指针
 */
StringHandler::StringHandler(QObject *parent)
    : SystemCallHandler(parent)
    , regexOptions(QRegularExpression::CaseInsensitiveOption)
{
    qDebug() << "StringHandler已创建";
    // 初始化编码器映射
    codecMap[StringEncoding::Utf8] = QTextCodec::codecForName("UTF-8");
    codecMap[StringEncoding::Ascii] = QTextCodec::codecForName("ASCII");
    codecMap[StringEncoding::Latin1] = QTextCodec::codecForName("ISO 8859-1");
    codecMap[StringEncoding::Utf16] = QTextCodec::codecForName("UTF-16");
}

/**
 * @brief StringHandler析构函数
 */
StringHandler::~StringHandler()
{
    qDebug() << "StringHandler已销毁";
    // Qt对象会自动清理
}

/**
 * @brief 处理字符串操作中断
 * @param interruptNumber 中断号 (0x30-0x3F)
 * @param cpu CPU模拟器引用
 * @return SystemCallResult 处理结果
 */
SystemCallResult StringHandler::handleInterrupt(int interruptNumber, CpuSimulator* cpu)
{
    if (!cpu) {
        return createErrorResult(-1, "CPU模拟器指针为空");
    }

    switch (interruptNumber) {
        case 0x30: return handleStringLength(cpu);
        case 0x31: return handleStringCopy(cpu);
        case 0x32: return handleStringCompare(cpu);
        case 0x33: return handleStringConcatenate(cpu);
        case 0x34: return handleStringFind(cpu);
        case 0x35: return handleStringReplace(cpu);
        case 0x36: return handleStringConversion(cpu);
        case 0x37: return handleStringSplit(cpu);
        case 0x38: return handleSubstring(cpu);
        case 0x39: return handleStringInsert(cpu);
        case 0x3A: return handleStringDelete(cpu);
        case 0x3B: return handleCharacterCount(cpu);
        case 0x3C: return handleStringEncoding(cpu);
        case 0x3D: return handleRegexMatch(cpu);
        case 0x3E: return handleStringHash(cpu);
        case 0x3F: return handleStringFormat(cpu);
        default:
            return createErrorResult(-2, QString("不支持的字符串中断: 0x%1").arg(interruptNumber, 2, 16, QChar('0')));
    }
}

/**
 * @brief 获取支持的中断号范围
 * @return QPair<int, int> 中断号范围
 */
QPair<int, int> StringHandler::getSupportedInterruptRange() const
{
    return qMakePair(0x30, 0x3F);
}

/**
 * @brief 获取处理器描述
 * @return QString 处理器描述
 */
QString StringHandler::getDescription() const
{
    return "字符串操作处理器 - 提供字符串长度、复制、比较、连接等功能";
}

/**
 * @brief 重置处理器状态
 */
void StringHandler::reset()
{
    // 字符串处理器无需特殊重置
    regexOptions = QRegularExpression::CaseInsensitiveOption;
}

/**
 * @brief INT 0x30 - 计算字符串长度
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult StringHandler::handleStringLength(CpuSimulator* cpu)
{
    int stringAddr = cpu->getRegister("AX");
    QString str = readStringFromMemory(cpu, stringAddr);
    
    QMap<QString, int> resultMap;
    resultMap["BX"] = str.length();
    
    emit outputMessage(QString("字符串长度: %1").arg(str.length()));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x31 - 字符串复制
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult StringHandler::handleStringCopy(CpuSimulator* cpu)
{
    int srcAddr = cpu->getRegister("AX");
    int destAddr = cpu->getRegister("BX");
    
    QString srcStr = readStringFromMemory(cpu, srcAddr);
    int bytesCopied = writeStringToMemory(cpu, destAddr, srcStr);
    
    QMap<QString, int> resultMap;
    resultMap["CX"] = bytesCopied;
    
    emit outputMessage(QString("字符串复制完成: %1 字节").arg(bytesCopied));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x32 - 字符串比较
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult StringHandler::handleStringCompare(CpuSimulator* cpu)
{
    int str1Addr = cpu->getRegister("AX");
    int str2Addr = cpu->getRegister("BX");
    
    QString str1 = readStringFromMemory(cpu, str1Addr);
    QString str2 = readStringFromMemory(cpu, str2Addr);
    
    int result = str1.compare(str2);
    if (result > 0) result = 1;
    else if (result < 0) result = -1;
    
    QMap<QString, int> resultMap;
    resultMap["CX"] = result;
    
    emit outputMessage(QString("字符串比较结果: %1").arg(result));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x33 - 字符串连接
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult StringHandler::handleStringConcatenate(CpuSimulator* cpu)
{
    int str1Addr = cpu->getRegister("AX");
    int str2Addr = cpu->getRegister("BX");
    int resultAddr = cpu->getRegister("CX");
    
    QString str1 = readStringFromMemory(cpu, str1Addr);
    QString str2 = readStringFromMemory(cpu, str2Addr);
    QString result = str1 + str2;
    
    int bytesWritten = writeStringToMemory(cpu, resultAddr, result);
    
    QMap<QString, int> resultMap;
    resultMap["DX"] = result.length();
    
    emit outputMessage(QString("字符串连接完成: 长度 %1").arg(result.length()));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x34 - 字符串查找
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult StringHandler::handleStringFind(CpuSimulator* cpu)
{
    int srcAddr = cpu->getRegister("AX");
    int searchAddr = cpu->getRegister("BX");
    
    QString srcStr = readStringFromMemory(cpu, srcAddr);
    QString searchStr = readStringFromMemory(cpu, searchAddr);
    
    int position = srcStr.indexOf(searchStr);
    
    QMap<QString, int> resultMap;
    resultMap["CX"] = position;
    
    emit outputMessage(QString("字符串查找结果: 位置 %1").arg(position));
    
    return createSuccessResult(resultMap);
}

/**
 * @brief INT 0x36 - 字符串格式转换
 * @param cpu CPU模拟器指针
 * @return SystemCallResult 处理结果
 */
SystemCallResult StringHandler::handleStringConversion(CpuSimulator* cpu)
{
    int stringAddr = cpu->getRegister("AX");
    int conversionType = cpu->getRegister("BX");
    
    QString str = readStringFromMemory(cpu, stringAddr);
    StringConversion conversion = static_cast<StringConversion>(conversionType);
    
    QString result = performStringConversion(str, conversion);
    writeStringToMemory(cpu, stringAddr, result); // 原地修改
    
    QMap<QString, int> resultMap;
    resultMap["CX"] = 0; // 成功
    
    emit outputMessage(QString("字符串转换完成"));
    
    return createSuccessResult(resultMap);
}

// 辅助方法实现

/**
 * @brief 从内存中读取字符串
 * @param cpu CPU模拟器指针
 * @param address 字符串地址
 * @return QString 读取的字符串
 */
QString StringHandler::readStringFromMemory(CpuSimulator* cpu, int address)
{
    QString result;
    int currentAddr = address;
    
    while (currentAddr < address + MAX_STRING_LENGTH) {
        int charValue = cpu->getMemory(currentAddr);
        if (charValue == 0) {
            break; // 遇到字符串结束符
        }
        
        result.append(QChar(charValue));
        currentAddr++;
    }
    
    return result;
}

/**
 * @brief 向内存写入字符串
 * @param cpu CPU模拟器指针
 * @param address 目标地址
 * @param str 字符串
 * @param maxLength 最大长度
 * @return int 实际写入长度
 */
int StringHandler::writeStringToMemory(CpuSimulator* cpu, int address, const QString& str, int maxLength)
{
    int actualLength = qMin(str.length(), maxLength > 0 ? maxLength - 1 : MAX_STRING_LENGTH - 1);
    
    for (int i = 0; i < actualLength; ++i) {
        cpu->setMemory(address + i, str.at(i).unicode());
    }
    
    // 写入字符串结束符
    cpu->setMemory(address + actualLength, 0);
    
    return actualLength + 1; // 包括结束符
}

/**
 * @brief 执行字符串转换操作
 * @param str 源字符串
 * @param conversionType 转换类型
 * @return QString 转换后的字符串
 */
QString StringHandler::performStringConversion(const QString& str, StringConversion conversionType)
{
    switch (conversionType) {
        case StringConversion::ToUpperCase:
            return str.toUpper();
        case StringConversion::ToLowerCase:
            return str.toLower();
        case StringConversion::ToTitleCase:
            return str.toLower().replace(0, 1, str.at(0).toUpper());
        case StringConversion::Reverse:
            {
                QString reversed = str;
                std::reverse(reversed.begin(), reversed.end());
                return reversed;
            }
        case StringConversion::Trim:
            return str.trimmed();
        case StringConversion::TrimLeft:
            return str.trimmed(); // 简化实现
        case StringConversion::TrimRight:
            return str.trimmed(); // 简化实现
        default:
            return str;
    }
}

/**
 * @brief 计算字符串哈希值
 * @param str 输入字符串
 * @param algorithm 哈希算法类型
 * @return QByteArray 哈希值
 */
QByteArray StringHandler::calculateStringHash(const QString& str, QCryptographicHash::Algorithm algorithm)
{
    QCryptographicHash hash(algorithm);
    hash.addData(str.toUtf8());
    return hash.result();
}

/**
 * @brief 获取字符串编码类型对应的QTextCodec
 * @param encoding 编码类型
 * @return QTextCodec* 编码器指针
 */
QTextCodec* StringHandler::getTextCodec(StringEncoding encoding)
{
    return codecMap.value(encoding, QTextCodec::codecForName("UTF-8"));
}

// 占位实现其他方法
SystemCallResult StringHandler::handleStringReplace(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult StringHandler::handleStringSplit(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult StringHandler::handleSubstring(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult StringHandler::handleStringInsert(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult StringHandler::handleStringDelete(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult StringHandler::handleCharacterCount(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult StringHandler::handleStringEncoding(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult StringHandler::handleRegexMatch(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult StringHandler::handleStringHash(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }
SystemCallResult StringHandler::handleStringFormat(CpuSimulator* cpu) { Q_UNUSED(cpu) return createSuccessResult(); }

QStringList StringHandler::readStringArrayFromMemory(CpuSimulator* cpu, int address, int count) { Q_UNUSED(cpu) Q_UNUSED(address) Q_UNUSED(count) return {}; }
int StringHandler::writeStringArrayToMemory(CpuSimulator* cpu, int address, const QStringList& strings) { Q_UNUSED(cpu) Q_UNUSED(address) Q_UNUSED(strings) return 0; }
QByteArray StringHandler::performEncodingConversion(const QString& str, StringEncoding fromEncoding, StringEncoding toEncoding) { Q_UNUSED(str) Q_UNUSED(fromEncoding) Q_UNUSED(toEncoding) return {}; }
bool StringHandler::performRegexMatch(const QString& text, const QString& pattern, int& matchPosition) { Q_UNUSED(text) Q_UNUSED(pattern) Q_UNUSED(matchPosition) return false; }
bool StringHandler::validateStringParameters(const QString& operation, int address, int length) { Q_UNUSED(operation) Q_UNUSED(address) Q_UNUSED(length) return true; }
QString StringHandler::formatString(const QString& format, const QList<QVariant>& args) { Q_UNUSED(format) Q_UNUSED(args) return ""; } 